SERVICE_TEL = 10096;
CLIENT_ACCESS_KEY = "3974e55e5f710765248cbe838f13b4f7";
CLIENT_APPID = "4974e55e5f710765248cbe838f13b4f7";
//var HOST = "http://219.148.159.73:9999";
var HOST = "http://192.168.1.128" ;
var EMC_HOST = "http://121.18.114.66:8091/xhz-emc";
//var EMC_HOST = "http://172.18.3.40:8085";
 

// 登陆地址
var EMC_URL_LOGIN =  EMC_HOST + "/common/login";
// 同步client地址
var EMC_SYNC_CLIENT = EMC_HOST + "/common/push/sync/client/user";
// 工单列表
var EMC_URL_TASK = EMC_HOST + "/api/worker/order/query";
// 工单详情
var EMC_URL_TASK_DETAIL = EMC_HOST + "/api/worker/order/detail";
// 确认接收工单
var EMC_URL_TASK_ACCEPT = EMC_HOST + "/api/worker/order/accept";
// 拒绝接收工单
var EMC_URL_TASK_REFUSE = EMC_HOST + "/api/worker/order/refuse";
// 完成工单
var EMC_URL_TASK_COMPLETE = EMC_HOST + "/api/worker/order/complete";
// 同步client地址
var EMC_SYNC_CLIENT = EMC_HOST + "/common/push/sync/client/user";
// 下载工单附件
var EMC_DOWNLOAD_FILE = EMC_HOST + "/common/workorder/download";

var URL_LOGIN =  HOST + "/common/login";
//通知配置
var URL_PROFIL_SET = HOST + "/common/message/seting";
// 同步client地址
var SYNC_CLIENT = HOST + "/common/push/sync/client/user";
//版本检查
var URL_VERSION = HOST + "/common/app/version";
// 公告列表
var URL_NOTICE = HOST + "/api/notice/list";
// 公告详情
var URL_NOTICE_DETAIL = HOST + "/api/notice/detail";
// 工单列表
var URL_TASK = HOST + "/api/worker/order/query";
// 工单详情
var URL_TASK_DETAIL = HOST + "/api/worker/order/detail";
// 确认接收工单
var URL_TASK_ACCEPT = HOST + "/api/worker/order/accept";
// 拒绝接收工单
var URL_TASK_REFUSE = HOST + "/api/worker/order/refuse";
// 延时接收工单
var URL_TASK_DELAY = HOST + "/api/worker/order/delay";
// 完成工单
var URL_TASK_COMPLETE = HOST + "/api/worker/order/complete";
// 工单延时
var URL_TASK_DELAY = HOST + "/api/worker/order/delay";

var tashStatus = {
	unaccept: 'unaccept', //待接收
	goingon: 'goingon', //进行中
	delay: 'delay', //延时工单
	complete: 'complete', //已完成工单
	groups: 'groups' //组员工单
};
(function($, owner) {
	owner.post = function(url, data, successback, errorback) {
		successback = successback || $.noop;
		errorback = errorback || owner.error;
		data = data || {};

		if (data.debug) {
			return;
		}
		console.debug("post request data is " + JSON.stringify(data) + " request url is " + url);

		$.ajax(url, {
			data: data,
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			success: function(data) {
				console.debug("server resopnse is " + JSON.stringify(data));
				return successback(data);
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				errorback(xhr, type, errorThrown);
			}
		});
	};

	owner.token = function(data) {
		var user = owner.getUser() || {};
		data.appid = CLIENT_APPID;
		data.timestamp = Math.round(new Date().getTime() / 1000);
		data.noncestr = Math.uuid(15);
		data.ownerId = user.id || "";
		var signature = CLIENT_ACCESS_KEY + '|' + CLIENT_APPID + '|' + data.timestamp + '|' + data.noncestr + '|' + data.ownerId;
		data.token = md5(signature);

		return data;
	};

	owner.upload = function(url, data, successback) {
		successback = successback || $.noop;
		data = data || {};
		data = owner.token(data);
		plus.nativeUI.showWaiting("正在处理,请稍后");
		var task=plus.uploader.createUpload(url+'?timestamp='+data.timestamp,
	            { 
	            	method:"POST",
	            	blocksize:10000000,
	            	timeout: 60000,
	            	priority:100
	            },
	            function(t,status){
	            	plus.nativeUI.closeWaiting();
	            	if(200 == status){
//	            		task.clear() ;
	            		successback(t.responseText) ;
	            	}else{
	           	    	mui.alert("操作失败，请稍后再试");
	            	}
	            }
	        );
	        
	    if(data.files){
			mui.each(data.files , function(i ,item){
				var _path = plus.io.convertLocalFileSystemURL(item) ;
				task.addFile(_path,{key:'file_'+i});
				console.debug('_path is  ' + _path) ;
			}) ;
		}
	    
	    task.addData("taskId" ,data.taskId || '') ;
	    task.addData("description" ,data.description || '') ;
		
		console.debug('data  is  ' + JSON.stringify(data)) ;
		
		task.addData("appid",data.appid);
	//	task.addData("timestamp",data.timestamp);
		task.addData("noncestr",data.noncestr);
		task.addData("ownerId",data.ownerId);
		task.addData("signature",data.signature);
		task.addData("token",data.token);
		
		task.start() ;
	};

	owner.ajax = function(url, data, successback, errorback) {
		successback = successback || $.noop;
		errorback = errorback || owner.error;
		data = data || {};
		data = owner.token(data);

		console.debug("request data is " + JSON.stringify(data) + " request url is " + url);
		if (data.debug) {
			return;
		}

		$.ajax(url, {
			data: data,
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			success: function(data) {
				console.debug("server resopnse is " + JSON.stringify(data));
				return successback(data);
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				errorback(xhr, type, errorThrown);
			}
		});
	};

	owner.error = function(xhr, type, errorThrown) {
			if ('timeout' == type) {
				mui.toast('亲，服务端忙坏了，稍后再试试呢');
				return;
			}

			if (xhr && xhr.response) {
				var data = JSON.parse(xhr.response) || {};
				if (data.code) {
					mui.toast(data.message);
					return;
				}
			}
			mui.toast(xhr.response);
		}
		/**
		 * 获取当前pushClient状态
		 **/
	owner.getSyncClientState = function() {
		var stateText = localStorage.getItem('$push_client_state') || "{}";
		return JSON.parse(stateText);
	};

	/**
	 * 设置当前pushClient状态
	 **/
	owner.setSyncClientState = function(state) {
		state = state || {};
		localStorage.setItem('$push_client_state', JSON.stringify(state));
	};

	/**
	 * 获取当前状态
	 **/
	owner.getState = function() {
		var stateText = localStorage.getItem('$state') || "{}";
		return JSON.parse(stateText);
	};

	/**
	 * 设置当前状态
	 **/
	owner.setState = function(state) {
		state = state || {};
		localStorage.setItem('$state', JSON.stringify(state));
		//var settings = owner.getSettings();
		//settings.gestures = '';
		//owner.setSettings(settings);
	};

	/**
	 * 获取当前状态
	 **/
	owner.getUser = function() {
		var userText = localStorage.getItem('$xhz_user') || "{}";
		return JSON.parse(userText);
	};

	/**
	 * 设置当前状态
	 **/
	owner.setUser = function(user) {
		user = user || {};
		localStorage.setItem('$xhz_user', JSON.stringify(user));
	};
	
	/**
	 * 获取当前状态
	 **/
	owner.getUserName = function() {
		var userText = localStorage.getItem('$xhz_user_name') || "{}";
		return JSON.parse(userText);
	};

	/**
	 * 设置当前状态
	 **/
	owner.setUserName = function(user) {
		user = user || {};
		localStorage.setItem('$xhz_user_name', JSON.stringify(user));
	};

	/**
	 * 获取当前状态
	 **/
	owner.getTimestamp = function() {
		var userText = localStorage.getItem('$xhz_timestamp') || "{}";
		return JSON.parse(userText);
	};

	/**
	 * 设置当前状态
	 **/
	owner.setTimestamp = function(timestamp) {
		user = user || {};
		localStorage.setItem('$xhz_timestamp', JSON.stringify(timestamp));
	};

	var checkEmail = function(email) {
		email = email || '';
		return (email.length > 3 && email.indexOf('@') > -1);
	};

	/**
	 * 获取应用本地配置
	 **/
	owner.setSettings = function(settings) {
		settings = settings || {};
		localStorage.setItem('$settings', JSON.stringify(settings));
	}

	/**
	 * 设置应用本地配置
	 **/
	owner.getSettings = function() {
		var settingsText = localStorage.getItem('$settings') || "{}";
		return JSON.parse(settingsText);
	};

	/**
	 * 同步推送clientid
	 */
	owner.syncClient = function() {

		var clientInfo = plus.push.getClientInfo();
		var user = owner.getUser();
		/**数据不全不同步*/
		if (!clientInfo || !clientInfo.clientid ||
			'null' == clientInfo.clientid || !user || !user.id) {
			return;
		}

		var clientData = {
			alias: user.id,
			clientid: clientInfo.clientid,
			token: clientInfo.token,
			appid: clientInfo.appid,
			appkey: clientInfo.appkey
		};

		var orginal = owner.getSyncClientState();
		// 对比之前是否同步过 已同步则不再同步
		if (orginal && orginal.clientid &&
			orginal.clientid == clientData.clientid &&
			orginal.alias == clientData.alias) {
			return;
		}
		var user = owner.getUser() ;
		var loginType = user.loginType ? user.loginType*1 : 1 ;
		var sync_url = (2 == loginType ) ?EMC_SYNC_CLIENT: SYNC_CLIENT
		owner.post(sync_url, clientData, function(data) {
			if (data.code == 1) {
				owner.setSyncClientState(clientData);
				return true;
			}
			owner.setSyncClientState({});
			return false;
		}, function(xhr, type, errorThrown) {
			owner.setSyncClientState({});
			return false;
		})
	};

	owner.network = function() {
		var networkinfo = plus.networkinfo.getCurrentType();
		console.debug("networkinfo is "+networkinfo );
//		if (plus.networkinfo.CONNECTION_NONE == networkinfo || plus.networkinfo.CONNECTION_UNKNOW == networkinfo) {
//			return false;
//		} else {
//			return true;
//		}
		var types = {}; 
		  types[plus.networkinfo.CONNECTION_UNKNOW] = "Unknown connection"; 
		  types[plus.networkinfo.CONNECTION_NONE] = "No connection"; 
		  types[plus.networkinfo.CONNECTION_ETHERNET] = "Ethernet connection"; 
		  types[plus.networkinfo.CONNECTION_WIFI] = "WiFi connection"; 
		  types[plus.networkinfo.CONNECTION_CELL2G] = "Cellular 2G connection"; 
		  types[plus.networkinfo.CONNECTION_CELL3G] = "Cellular 3G connection"; 
		  types[plus.networkinfo.CONNECTION_CELL4G] = "Cellular 4G connection"; 
		
		  console.debug(types[plus.networkinfo.getCurrentType()]);
		  if (plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE 
		  || plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_UNKNOW) {
//		    mui.toast("当前暂无网络连接，请打开数据服务!", "提示");
			return false;
		  }else{
		  	return true;
		  }
			//获取当前网络类型
//			var nt = plus.networkinfo.getCurrentType();
//			console.debug("当前网络为："+nt);
//			switch(nt){
//			case plus.networkinfo.CONNECTION_ETHERNET:
//			case plus.networkinfo.CONNECTION_WIFI:
//				console.debug("当前网络为WiFi");
//				return true;
//				break;
//			case plus.networkinfo.CONNECTION_CELL2G:
//			case plus.networkinfo.CONNECTION_CELL3G:
//				console.debug("3G");
//				return true;
//				break;
//			case plus.networkinfo.CONNECTION_CELL4G:
//				console.debug("当前网络非WiFi");
//				return true;
//				break;
//			default:
//				console.debug("当前没有网络");
//				return false;
//				break;
//			}
	}

	owner.dateformat = function(timestamp, format) {
		format = format || 'yyyy-MM-dd h:m';
		var times = new Date(timestamp);
		var date = {
			"M+": times.getMonth() + 1,
			"d+": times.getDate(),
			"h+": times.getHours(),
			"m+": times.getMinutes(),
			"s+": times.getSeconds(),
			"q+": Math.floor((times.getMonth() + 3) / 3),
			"S+": times.getMilliseconds()
		};
		if (/(y+)/i.test(format)) {
			format = format.replace(RegExp.$1, (times.getFullYear() + '').substr(4 - RegExp.$1.length));
		}
		for (var k in date) {
			if (new RegExp("(" + k + ")").test(format)) {
				format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
			}
		}
		return format;
	};
	owner.getString = function(name) {;
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		var r = window.location.search.substr(1).match(reg);
		if (r != null) return unescape(r[2]);
		return null;
	};
	owner.update = function(tip) {
		plus.runtime.getProperty(plus.runtime.appid, function(info) {
			var version = info.version;
			var parmas = {
				"appid": plus.runtime.appid,
				//		"version":plus.runtime.version,
				"version": version,
				"innerVersion": plus.runtime.innerVersion,
				"imei": plus.device.imei
			};

			xhz.ajax(URL_VERSION, parmas, function(data) {

				console.debug(" data is " + JSON.stringify(data));
				if (data.code == 1) {
					var verInfo = data.data;
					if (version >= verInfo.vresion) {
						if (tip)
							mui.toast("亲，这个已经是最新的了哦");
						return;
					}
					plus.nativeUI.confirm("亲，有新版本啦，要更新吗？", function(event) {
						if (0 == event.index) {
							plus.runtime.openURL(verInfo.dowloadurl);
						}
					}, data.title, ["立即更新", "取消"]);
				}
			}, function(data) {
				// do Nothing
			});
		});
	}

}(mui, window.xhz = {}));